package common.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库连接对象
 */
public class DbUtil {

    //定义MySQL的数据库驱动程序
    public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
    //定义MySQL数据库的连接地址
    public static final String DBURL = "jdbc:mysql://xjumysqldb.mysql.cn-chengdu.rds.aliyuncs.com:3306/db_lcf";
    //MySQL数据库的连接用户名
    public static final String DBUSER = "lcf";
    //MySQL数据库的连接密码
    public static final String DBPASS = "Lcf915669640";

    public static Connection getCon() {
        Connection con = null;
        try {
            //加载驱动程序
            Class.forName(DBDRIVER);
            //连接MySQL数据库时，要写上连接的用户名和密码
            con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
            return con;
        }catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void closeCon(Connection con) throws SQLException {
        if (con != null) {
            con.close();
        }
    }

    /**
     * 测试连接状态
     */
    public static void main(String[] args) {
        try {
            getCon();
            System.out.println("数据库连接成功");
        } catch (Exception e) {
            System.out.println("数据库连接失败");
        }
    }
}
